package com.koron.css2.newProjectCenter.callback;

import com.koron.css2.newProjectCenter.bean.PjInfoBean;
import com.koron.css2.newProjectCenter.mapper.PjInfoMapper;
import com.koron.css2.serviceManage.bean.UserInfoBean;
import com.koron.css2.workflow.AbstractProcessInterface;
import com.koron.css2.workflow.ProcessInterface;
import com.koron.util.Constant;
import com.koron.util.SpringContextHolder;
import org.koron.ebs.mybatis.SessionFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.swan.bean.MessageBean;

import java.util.Map;

/**
 * 用户工程2.1 流程审批接口回调
 * 主要用于审批成功之后进行一些业务上的操作
 * @author amdin
 * @version 2.1
 * @since 2021-06-04
 */
public class PjInfoCallback extends AbstractProcessInterface {

    private static Logger logger = LoggerFactory.getLogger(PjInfoCallback.class);

    // 流程节点业务处理回调类
    public Map<String, IPjInfoNodeCallback> pjInfoNodeCallbackMap = SpringContextHolder.getBeansOfType(IPjInfoNodeCallback.class);

    @Override
    public MessageBean<?> before(SessionFactory factory, UserInfoBean userInfo, String billId, String fromNodeCode, int operation) {
        PjInfoMapper pjInfoMapper = factory.getMapper(PjInfoMapper.class);
        MessageBean<?> info = MessageBean.create(Constant.MESSAGE_INT_SUCCESS, "success", Void.class);
        try {
            PjInfoBean pjInfoBean = pjInfoMapper.selectById(billId);
            // 挂起中和已挂起单据不能进行审批操作
            if (pjInfoBean.getPendingState() != null && (pjInfoBean.getPendingState() == 2)||(pjInfoBean.getPendingState() == 1)){
                return MessageBean.create(Constant.MESSAGE_INT_FAIL, "该工程已挂起，如需操作请先恢复工程再提交内容", Void.class);
            }
            // 已终止的工程单或者终止审批中的工程单不能进行审批操作
            if (pjInfoBean.getTerminationFlag() != null && pjInfoBean.getTerminationFlag() == 1){
                return MessageBean.create(Constant.MESSAGE_INT_FAIL, "该工程单已终止，暂不能进行操作", Void.class);
            }
            // 流程审批【废弃】操作之后的回调
            if(operation == ProcessInterface.OPERATION_SUSPEND){
                PjTerminationCallback.pjTermination(factory, billId, fromNodeCode, pjInfoBean.getPjType());
            }
            // 流程审批【通过】操作之后的回调
            if(operation == ProcessInterface.OPERATION_AGREE){
                if (pjInfoNodeCallbackMap != null && pjInfoNodeCallbackMap.get(fromNodeCode) != null){
                    IPjInfoNodeCallback pjInfoNodeCallback = pjInfoNodeCallbackMap.get(fromNodeCode);
                    MessageBean message = pjInfoNodeCallback.callback(factory, pjInfoBean, userInfo);
                    if (message != null && Constant.MESSAGE_INT_SUCCESS != message.getCode()){
                        return message;
                    }
                }
            }
        } catch (Exception e) {
            logger.error("执行工程审批后续操作失败", e);
            info = MessageBean.create(Constant.MESSAGE_INT_FAIL, "执行工程审批后续操作失败", Void.class);
        }
        return info;
    }
}
